import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Register {
    private Socket socket;
    private Scanner scanner;

    public Register(Socket socket, Scanner scanner){
        this.socket=socket;
        this.scanner=scanner;
    }

    public void registerMethod() {
        //连接数据库
        Connection conn = DruidUtils.getConnection();
        PrintStream printStream = null; //输出流
        String name = null;
        String pwd = null;
        PreparedStatement ps = null;

        //用户输入Name
        name = scanner.nextLine();
        //用户输入pwd
        pwd = scanner.nextLine();
        //添加用户
        String sql;
        sql = "INSERT INTO user(userName,pwd) values(?,?)";

        //获取输出流
        try {
            printStream = new PrintStream(socket.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            ps.setString(2, pwd);
            ps.executeUpdate();

            //返回ID给用户

            rs = ps.getGeneratedKeys();
            if (rs.next()) {
                int userID = rs.getInt(1);
                printStream.println(String.valueOf(userID));
            }
        } catch (SQLException e) {
            printStream.println("0");
        }
        DruidUtils.closeAll(conn, ps, rs);
    }
}
